package com.saturn.titan.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * 导出
 * @author
 * @date
 */
@Component
public class ExportUtil {

	private static Logger logger = LoggerFactory.getLogger(ExportUtil.class);

	@Autowired
	private Configuration freemarkerConfig;

	/**
	 * 通过浏览器导出excel
	 * 
	 * @param response
	 * @param freemarkerTemplateName
	 * @param map
	 */
	public void exportExcel(HttpServletResponse response, String freemarkerTemplateName, String excelName,String excelType, Map<String, Object> map) {
		Writer out = null;
		try {
			response.reset(); // 清空输出流
			response.setContentType("application/msexcel;charset=utf-8");
			response.setHeader("Content-disposition", "attachment; filename=" + new String(excelName.getBytes("utf-8"),"ISO8859-1") + "." + excelType);// 设定输出文件头
			response.setCharacterEncoding("GBK");
			out = response.getWriter();
			Template template = freemarkerConfig.getTemplate(freemarkerTemplateName,"utf-8");
			template.setEncoding("UTF-8");
			
			template.process(map, out);
			
			if (out != null) {
				out.flush();
				out.close();
			}
		} catch (Exception e) {
			logger.error("导出excel失败", e);
			if (out != null) {
				try {
					out.close();
				} catch (IOException ignore) {
				}
			}
		}
	}

	/**
	 * 通过浏览器导出word
	 * 
	 * @param response
	 * @param freemarkerTemplateName
	 * @param map
	 */
	public void exportWord(HttpServletResponse response, String freemarkerTemplateName, String wordName, HashMap<String, Object> map) {
		Writer out = null;
		try {
			response.reset();// 清空输出流
			response.setContentType("application/msword;charset=utf-8");
			response.setHeader("Content-disposition", "attachment; filename=" + wordName + ".doc");// 设定输出文件头
			out = response.getWriter();
			Template template = freemarkerConfig.getTemplate(freemarkerTemplateName);
			template.setEncoding("utf-8");
			template.process(map, out);
			if (out != null) {
				out.flush();
				out.close();
			}
		} catch (Exception e) {
			logger.error("导出word失败", e);
			if (out != null) {
				try {
					out.close();
				} catch (IOException e1) {
					logger.error("导出word失败", e1);
				}
			}
		}
	}

	@SuppressWarnings("unused")
	private String formatTime(Date date, String pattern) {
		if (date == null) {
			return "";
		} else {
			return DateFormatUtils.format(date, pattern);
		}
	}

}
